package com.kr.aia.powerrp.telephone;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;

import com.kr.aia.powerrp.common.MainMovieClipListView;
import com.kr.aia.powerrp.common.RecController;
import com.kr.aia.powerrp.common.commonUtil;
import com.kr.aia.powerrp.db.CustomerDBUtil;
import com.kr.aia.powerrp.db.UserDBUtil;
import com.kr.aia.powerrp.db.UserInfoVO;
import com.kr.aia.powerrp.R;

public class TAModify extends Activity implements OnClickListener{
	private static final String TAG = "TARP";
    private ArrayList<Button> btArray = new ArrayList<Button>();
    
    private EditText ta_mod_text;
    private Button ta_mod_btn_home;
    
    private Button ta_mod_btn_reset;
    private Button ta_mod_btn_custname;
    private Button ta_mod_btn_recommender;
    private Button ta_mod_btn_relation;
    private Button ta_mod_btn_mpname;
    private Button ta_mod_btn_save;
    
    private ListView taMainView;
    private ArrayList<TADataVO> taData;
    private BaseAdapter taListAdapter;
    
    private int curSelectedContent = -1;
    
    
    public void setTaData(){
    	this.taData = new ArrayList<TADataVO>();
    	
    	FileInputStream fis = null;
    	BufferedReader br = null;
    	String strLine, strValue = "";
    	for(int i = 0 ; i < 15; i++){
    		try {
				fis = new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/powerRP/txt/ta/ta" + (i+1) + ".txt");
				br  = new BufferedReader(new InputStreamReader(fis));
				strValue = "";
				while( (strLine = br.readLine()) != null )
					strValue += strLine + "\n";
				
				this.taData.add(new TADataVO("title"+(i+1), strValue));
				//Log.e(TAG, this.taData.get(i).getContent());
			} catch (IOException e) {
				Toast toast = Toast.makeText(getApplicationContext(), "파일 저장에 실패하였습니다. 다시 시도하세요.", Toast.LENGTH_SHORT); 
				toast.show();
				finish();
			}
    	}
    }
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ta_modify);
        
        setTaData();
        
        commonUtil comUtil = new commonUtil();
        
        String dirName = "txt/ta";
        String dataPath = Environment.getExternalStorageDirectory().getPath() + "/powerRP/" + dirName;
        
        // 최초 실행시 폴더가 없으면 폴더 생성
        if(!comUtil.isDirectory(dataPath)){
        	File file;
        	FileOutputStream fos = null;
			for(int i = 0; i < 15; i++){
				file = new File(Environment.getExternalStorageDirectory().getPath() + "/powerRP/txt/ta/ta" + (i+1) + ".txt");
				// 최초 실행시 파일이 없으면 파일 생성
				if(!file.exists()) {
					try{
						fos = new FileOutputStream(file);
						fos.write((getResources().getString(R.string.ta_content_1+(i*2))).getBytes());
						fos.close();
					}catch(IOException e){
						Toast toast = Toast.makeText(getApplicationContext(), "데이터 초기화에 실패하였습니다. 다시 시도하세요.", Toast.LENGTH_SHORT); 
						toast.show();
						finish();
					}
				}
			}
        }
        
        
        
        ta_mod_text				= (EditText) findViewById(R.id.ta_mod_text);
        ta_mod_btn_home			= (Button) findViewById(R.id.ta_mod_btn_home);
        
        ta_mod_btn_reset		= (Button) findViewById(R.id.ta_mod_btn_reset);
        ta_mod_btn_custname 	= (Button) findViewById(R.id.ta_mod_btn_custname);
        ta_mod_btn_recommender	= (Button) findViewById(R.id.ta_mod_btn_recommender);
        ta_mod_btn_relation		= (Button) findViewById(R.id.ta_mod_btn_relation);
        ta_mod_btn_mpname		= (Button) findViewById(R.id.ta_mod_btn_mpname);
        ta_mod_btn_save			= (Button) findViewById(R.id.ta_mod_btn_save);
        
        
        for(int i = 0 ; i < 15; i++){
        	int ta_mod_id = getResources().getIdentifier("ta_mod_list" + (i+1), "id", getPackageName());
        	btArray.add(i, (Button) findViewById(ta_mod_id));
        }
        
        ta_mod_btn_home.setOnClickListener(this);
        ta_mod_btn_reset.setOnClickListener(this);
        ta_mod_btn_custname.setOnClickListener(this);
        ta_mod_btn_recommender.setOnClickListener(this);
        ta_mod_btn_relation.setOnClickListener(this);
        ta_mod_btn_mpname.setOnClickListener(this);
        ta_mod_btn_save.setOnClickListener(this);
        
		
		for(int i=0; i < 15; i++){
			btArray.get(i).setOnClickListener(this);
		}
		
		ta_mod_text.setMovementMethod(new ScrollingMovementMethod());
		
    }
    
    @Override
    public void onClick(View v){
    	int start = ta_mod_text.getSelectionStart();
		int end = ta_mod_text.getSelectionEnd();
		String txt;
		
    	switch(v.getId()){
    		case R.id.ta_mod_btn_home:
    			finish();
    			break;
    		case R.id.ta_mod_btn_reset:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
    				ta_mod_text.setText("");
        			ta_mod_text.setText(getResources().getString(R.string.ta_content_1 + (curSelectedContent*2)));
    			}
    			break;
    		case R.id.ta_mod_btn_custname:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
	    			txt = "_고객명_";
	    			ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
    			}
    			break;
    		case R.id.ta_mod_btn_recommender:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
	    			txt = "_추천인_";
	    			ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
    			}
    			break;
    		case R.id.ta_mod_btn_relation:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
	    			txt = "_관계_";
	    			ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
    			}
    			break;
    		case R.id.ta_mod_btn_mpname:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
	    			txt = "_MP명_";
	    			ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
    			}
    			break;
    		case R.id.ta_mod_btn_save:
    			if(curSelectedContent == -1){
    				showToast("내용을 먼저 선택하세요.");
    			}else{
	    			File file;
	            	FileOutputStream fos = null;
	            	
					file = new File(Environment.getExternalStorageDirectory().getPath() + "/powerRP/txt/ta/ta" + (curSelectedContent+1) + ".txt");
					// 최초 실행시 파일이 없으면 파일 생성
					if(file.exists()) {
						try{
							fos = new FileOutputStream(file);
							fos.write((ta_mod_text.getText().toString()).getBytes());

							showToast("저장되었습니다.");
							setTaData();
							fos.close();
						}catch(IOException e){
							showToast("저장에 실패하였습니다. 다시 시도하세요.");
							finish();
						}
					}
    			}
    			break;
    		case R.id.ta_mod_list1:
    			setContent(0);
    			break;
    		case R.id.ta_mod_list2:
    			setContent(1);
    			break;
    		case R.id.ta_mod_list3:
    			setContent(2);
    			break;
    		case R.id.ta_mod_list4:
    			setContent(3);
    			break;
    		case R.id.ta_mod_list5:
    			setContent(4);
    			break;
    		case R.id.ta_mod_list6:
    			setContent(5);
    			break;
    		case R.id.ta_mod_list7:
    			setContent(6);
    			break;
    		case R.id.ta_mod_list8:
    			setContent(7);
    			break;
    		case R.id.ta_mod_list9:
    			setContent(8);
    			break;
    		case R.id.ta_mod_list10:
    			setContent(9);
    			break;
    		case R.id.ta_mod_list11:
    			setContent(10);
    			break;
    		case R.id.ta_mod_list12:
    			setContent(11);
    			break;
    		case R.id.ta_mod_list13:
    			setContent(12);
    			break;
    		case R.id.ta_mod_list14:
    			setContent(13);
    			break;
    		case R.id.ta_mod_list15:
    			setContent(14);
    			break;
    	}
    	
    }
    
    public void setContent(int idx){
    	int len = ta_mod_text.length();
    	
    	ta_mod_text.setText(taData.get(idx).getContent());
		curSelectedContent = idx;
		
    	len = ta_mod_text.length();
    	ta_mod_text.setSelection(len);
    }
    
    private void showToast(String msg) {
        Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.show();
    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
        //return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
            	recorderController.startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                recorderController.releaseMediaRecorder();
            }
            break;

        case 1: //GoToAllNotes
        	recorderController.stopRecording();
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    */
}